package com.foreveross.minigames.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.foreveross.minigames.application.AnswerService;
import com.foreveross.minigames.application.UserService;
import com.foreveross.minigames.entity.Answer;
import com.foreveross.minigames.entity.Questions;
import com.foreveross.minigames.entity.User;
import com.foreveross.minigames.support.Constants;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class GamesController {

    @Autowired
    private UserService userService;

    @Autowired
    private AnswerService answerService;

    @GetMapping("/index")
    public ModelAndView welcome() {
        ModelAndView modelAndView = new ModelAndView("index");
        return modelAndView;
    }

    @GetMapping("/user")
    public ModelAndView info() {
        ModelAndView modelAndView = new ModelAndView("info");
        return modelAndView;
    }

    @PostMapping("/user")
    public String User(HttpServletRequest request, User user, Model model) {
        HttpSession session = request.getSession();
        User memoryUser = (User) session.getAttribute("user");
        if ( memoryUser == null ) {
            if ( StringUtils.isEmpty(user.getDepartmentName())
                    || StringUtils.isEmpty(user.getUserName()) ) {
                return "redirect:/user";
            }
            //QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            //queryWrapper.eq("department_name", user.getDepartmentName()).eq("user_name", user.getUserName());
            //List<User> list = userService.list(queryWrapper);
            //if ( !CollectionUtils.isEmpty(list) ) {
            //    User existUser = list.get(0);
            //    existUser.setBeginDate(new Date());
            //    existUser.setEndDate(null);
            //    existUser.setDuration(null);
            //    userService.updateById(existUser);
            //    user = existUser;
            //} else {
                user.setBeginDate(new Date());
                userService.save(user);
            //}
            session.setAttribute("user", user);
        }
        return "redirect:/question?questionId=0";
    }

    @RequestMapping("/question")
    public String toPage(HttpServletRequest request, HttpSession session, Model model,
                         Answer answer) {
        if ( answer != null && !StringUtils.isEmpty(answer.getUserAnswer()) ) {

            User userbyId = userService.getById(answer.getUserId());
            if(Objects.equals(answer.getQuestionId(),1)){
                try {
                    userbyId.setAnswerOne(get1024(Integer.parseInt(answer.getUserAnswer())).toString());
                } catch ( NumberFormatException e ) {
                    answer.setUserAnswer("");
                }
            }else if(Objects.equals(answer.getQuestionId(),2)){
                userbyId.setAnswerTwo(answer.getUserAnswer());
            }else if(Objects.equals(answer.getQuestionId(),3)){
                userbyId.setAnswerThird(answer.getUserAnswer());
            }else if(Objects.equals(answer.getQuestionId(),4)){
                userbyId.setAnswerFour(answer.getUserAnswer());
            }
            userService.updateById(userbyId);
            session.setAttribute("user", userbyId);
        }
        if ( StringUtils.isEmpty(request.getParameter("questionId")) ) {
            return "redirect:/question?questionId=1";
        }
        Integer questionId = Integer.parseInt(request.getParameter("questionId"));

        Questions questions = Constants.MAP.get(Constants.MAP.get(questionId).getNextPage());
        String CurrentPage = questions.getCurrentPage();
        model.addAttribute("question", questions);
        return CurrentPage;
    }


    @PostMapping("/operation")
    @ResponseBody
    public String operation(@RequestParam("fillName") String fillName) {
        StringBuffer stringBuffer = null;
        try {
            stringBuffer = get1024(Integer.parseInt(fillName));
        } catch ( NumberFormatException e ) {
            return "";
        }
        return stringBuffer.toString();
    }

    @PostMapping("/check")
    @ResponseBody
    public Map<String, Object> check(@RequestParam("fillName") String fillName, HttpSession session) {
        Map<String, Object> map = Maps.newHashMap();
        if ( !StringUtils.isEmpty(fillName) ) {
            if ( Constants.MAP.get(4).getAnswer().equals(fillName) ) {
                map.put("success", true);
                User memoryUser = (User) session.getAttribute("user");
                Date date = new Date();
                memoryUser.setEndDate(date);
                memoryUser.setDuration((memoryUser.getEndDate().getTime() - memoryUser.getBeginDate().getTime()) /
                        1000);
                userService.updateById(memoryUser);
                return map;
            }
        }
        map.put("success", false);
        map.put("msg", "答案错误");
        return map;
    }

    @GetMapping("/check")
    public String last() {
        return "last";
    }

    private StringBuffer get1024(Integer fillName) {
        StringBuffer stringBuffer = new StringBuffer();
        String findStr = "f%oer7e%vbecr%o9s6s";
        int b = fillName >> 10;
        for ( int i = 0; i < findStr.length(); i++ ) {
            String s = findStr.substring(i, i + 1);
            int t = i & b;
            if ( t == 1 ) {
                stringBuffer.append(s);
            }
        }
        return stringBuffer;
    }

    @RequestMapping("/exit")
    public String exit(HttpSession session) {
        User memoryUser = (User) session.getAttribute("user");
        if ( memoryUser != null && memoryUser.getId() != null ) {
            userService.removeById(memoryUser.getId());
        }
        return "redirect:/index";
    }

    @GetMapping("/users")
    public String users(Model model) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("duration");
        model.addAttribute("users",userService.list(queryWrapper));
        return "statistics";
    }
}
